package com.css.zfzx.sjcj.modules.hddcAviationMagnetic.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcActiveFault.viewobjects.HddcActivefaultVO;
import com.css.zfzx.sjcj.modules.hddcAviationMagnetic.repository.HddcAviationmagneticNativeRepository;
import com.css.zfzx.sjcj.modules.hddcAviationMagnetic.repository.HddcAviationmagneticRepository;
import com.css.zfzx.sjcj.modules.hddcAviationMagnetic.repository.entity.HddcAviationmagneticEntity;
import com.css.zfzx.sjcj.modules.hddcAviationMagnetic.service.HddcAviationmagneticService;
import com.css.zfzx.sjcj.modules.hddcAviationMagnetic.viewobjects.HddcAviationmagneticQueryParams;
import com.css.zfzx.sjcj.modules.hddcAviationMagnetic.viewobjects.HddcAviationmagneticVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-26
 */
@Service
public class HddcAviationmagneticServiceImpl implements HddcAviationmagneticService {

	@Autowired
    private HddcAviationmagneticRepository hddcAviationmagneticRepository;
    @Autowired
    private HddcAviationmagneticNativeRepository hddcAviationmagneticNativeRepository;

    @Override
    public JSONObject queryHddcAviationmagnetics(HddcAviationmagneticQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcAviationmagneticEntity> hddcAviationmagneticPage = this.hddcAviationmagneticNativeRepository.queryHddcAviationmagnetics(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcAviationmagneticPage);
        return jsonObject;
    }


    @Override
    public HddcAviationmagneticEntity getHddcAviationmagnetic(String id) {
        HddcAviationmagneticEntity hddcAviationmagnetic = this.hddcAviationmagneticRepository.findById(id).orElse(null);
         return hddcAviationmagnetic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcAviationmagneticEntity saveHddcAviationmagnetic(HddcAviationmagneticEntity hddcAviationmagnetic) {
        String uuid = UUIDGenerator.getUUID();
        hddcAviationmagnetic.setUuid(uuid);
        hddcAviationmagnetic.setCreateUser(PlatformSessionUtils.getUserId());
        hddcAviationmagnetic.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcAviationmagnetic.setIsValid("1");
        hddcAviationmagnetic.setQualityinspectionStatus("0");
        hddcAviationmagnetic.setExtends10("1");
        this.hddcAviationmagneticRepository.save(hddcAviationmagnetic);
        return hddcAviationmagnetic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcAviationmagneticEntity> saveHddcAviationmagneticList(List<HddcAviationmagneticEntity> list) {
        for (HddcAviationmagneticEntity hddcAviationmagnetic : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcAviationmagnetic.setUuid(uuid);
            hddcAviationmagnetic.setCreateUser(PlatformSessionUtils.getUserId());
            hddcAviationmagnetic.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcAviationmagnetic.setIsValid("1");
            hddcAviationmagnetic.setQualityinspectionStatus("0");
            hddcAviationmagnetic.setExtends10("1");
        }

        return hddcAviationmagneticNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcAviationmagneticEntity updateHddcAviationmagnetic(HddcAviationmagneticEntity hddcAviationmagnetic) {
        HddcAviationmagneticEntity entity = hddcAviationmagneticRepository.findById(hddcAviationmagnetic.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcAviationmagnetic);
        hddcAviationmagnetic.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcAviationmagnetic.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcAviationmagneticRepository.save(hddcAviationmagnetic);
        return hddcAviationmagnetic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcAviationmagnetics(List<String> ids) {
        List<HddcAviationmagneticEntity> hddcAviationmagneticList = this.hddcAviationmagneticRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcAviationmagneticList) && hddcAviationmagneticList.size() > 0) {
            for(HddcAviationmagneticEntity hddcAviationmagnetic : hddcAviationmagneticList) {
//                this.hddcAviationmagneticRepository.delete(hddcAviationmagnetic);
                hddcAviationmagnetic.setIsValid("0");
                hddcAviationmagnetic.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcAviationmagnetic.setUpdateTime(new Date());
                this.hddcAviationmagneticRepository.save(hddcAviationmagnetic);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcAviationmagneticQueryParams queryParams, HttpServletResponse response) {
        List<HddcAviationmagneticEntity> yhDisasterEntities = hddcAviationmagneticNativeRepository.exportYhDisasters(queryParams);
        List<HddcAviationmagneticVO> list=new ArrayList<>();
        for (HddcAviationmagneticEntity entity:yhDisasterEntities) {
            HddcAviationmagneticVO yhDisasterVO=new HddcAviationmagneticVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "航磁-线", "航磁-线", HddcAviationmagneticVO.class, "航磁-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcAviationmagneticVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcAviationmagneticVO.class, params);
            List<HddcAviationmagneticVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcAviationmagneticVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcAviationmagneticVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    public void saveDisasterList( List<HddcAviationmagneticVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcAviationmagneticEntity yhDisasterEntity = new HddcAviationmagneticEntity();
            HddcAviationmagneticVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcAviationmagnetic(yhDisasterEntity);
        }
    }
    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcAviationmagneticEntity> hddcA1InvrgnhasmaterialtableList = this.hddcAviationmagneticRepository.queryByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcAviationmagneticEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcAviationmagneticRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcAviationmagneticEntity> hddcA1InvrgnhasmaterialtableList = this.hddcAviationmagneticRepository.queryByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcAviationmagneticEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcAviationmagneticRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("Magnitude")){
            str+="Magnitude,";
        }
        if(!set.contains("MagnitudeName")){
            str+="MagnitudeName,";
        }
        if(!set.contains("ShowCode")){
            str+="ShowCode,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveHddcAviationmagneticFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcAviationmagneticEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcAviationmagneticEntity data = new HddcAviationmagneticEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setMagnitude(Integer.valueOf(obs.get(2).toString()));
                data.setMagnitudename(obs.get(3).toString());
                data.setShowcode(Integer.valueOf(obs.get(4).toString()));
                data.setCommentInfo(obs.get(5).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcAviationmagneticList(datas);
        }
    }

    @Override
    public List<HddcAviationmagneticEntity> findAll() {
        List<HddcAviationmagneticEntity> list=this.hddcAviationmagneticRepository.findAll();
        return list;

    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcAviationmagneticRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcAviationmagneticEntity> hddcAviationmagneticList = this.hddcAviationmagneticRepository.queryHddcAviationmagneticByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcAviationmagneticList) && hddcAviationmagneticList.size() > 0) {
            hddcAviationmagneticRepository.deleteAll(hddcAviationmagneticList);
        }
    }

}
